package com.mazaiting.jetpack.architecture.paging.custom

import android.arch.paging.PositionalDataSource
import java.util.*

private val CHEESE_DATA = arrayListOf(
        "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
        "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
        "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
        "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
        "Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
        "Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
        "Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
        "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
        "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
        "Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
        "Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
        "Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
        "Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)"
)
/**
 * 数据源
 * Created by mazaiting on 2018/7/26.
 */
class StudentDataSource : PositionalDataSource<Student>() {
  /**
   * 范围加载
   */
  override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<Student>) {
    // 回调结果
    callback.onResult(loadRangeInternal(params.startPosition, params.loadSize))
  }
  
  /**
   * 加载初始化
   */
  override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<Student>) {
    // 全部数据数量
    val totalCount = computeCount()
    // 当前位置
    val position = computeInitialLoadPosition(params, totalCount)
    // 加载数量
    val loadSize = computeInitialLoadSize(params, position, totalCount)
    // 回调结果
    callback.onResult(loadRangeInternal(position, loadSize), position, totalCount)
  }
  
  /**
   * 加载网络数据
   */
  private fun loadRangeInternal(position: Int, loadSize: Int): MutableList<Student> {
    // 创建列表
    val list = arrayListOf<Student>()
    // 遍历列表数据
    CHEESE_DATA.mapIndexed { index, text -> list.add(Student(index, text)) }
    // 设置加载数据
    var size = loadSize
    // 判断加载的位置是否大于总数据
    if (position >= computeCount()) {
      // 返回空数据
      return Collections.emptyList()
    }
    // 判断总条数是否大于计算的数据
    if (position + loadSize > computeCount()) {
      size = computeCount() - position - 1
    }
//    L.e("${computeCount()}:: $position :: $size" )
    // 返回子列表
    return list.subList(position, size + position)
  }
  
  /**
   * 总条数
   */
  private fun computeCount(): Int = CHEESE_DATA.size
  
}